<script setup lang="ts">
import { useRouter, RouterView, RouterLink } from 'vue-router'
import { getMenuData, clearMenuItem, type RouteContextProps } from '@ant-design-vue/pro-layout'

import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { checkDeviceType } from '@/hooks/util'
import { message } from 'ant-design-vue'
import { useBrandStore } from '@/store/modules/brand'

const userStore = useUserStore()

const { userInfo, nowRouter, newRouterList } = storeToRefs(userStore)

const brandStore = useBrandStore()

// console.log('brandStore=', brandStore.documentTitle)

const usePermission = usePermissionStore()
const { routers } = storeToRefs(usePermission)

if (userInfo.value.role !== 'ADMIN') {
  routers.value[0].children = routers.value[0].children?.filter(function (item) {
    return item.name !== 'userPedigree'
  })
}

let reallyMenuData = routers.value.find(item => item.name === 'index')!.children

if (!brandStore.promotionCenter) {
  reallyMenuData = reallyMenuData?.filter(item => item.path != '/promotion-center')
}

reallyMenuData = reallyMenuData?.map(item => {
  if (item.name == 'promotionCenter' && brandStore.documentTitle == '票务之家') {
    item.path = 'http://www.wczj.vip'
    // @ts-ignore
    item.meta.target = '_blank'
    // @ts-ignore
    item.meta.title = '网创之家'
  }
  return item
})

// console.log('reallyMenuData=', reallyMenuData)

import logoImg from '@/assets/logo.png'

const router = useRouter()
const { menuData } = getMenuData(clearMenuItem(router.getRoutes()))
// console.log('menuData=', menuData)

const state = reactive<Omit<RouteContextProps, 'reallyMenuData'>>({
  collapsed: false, // default collapsed
  selectedKeys: [], // default selectedKeys
  openKeys: [], // defualt openKeys
})

const loading = ref(false)

const proConfig = ref({
  layout: 'side',
  navTheme: 'light',
  fixedHeader: true,
  fixSiderbar: true,
  splitMenus: true,
})

const breadcrumb = computed(() =>
  router.currentRoute.value.matched.concat().map(item => {
    return {
      path: item.path,
      breadcrumbName: item.meta.title || '',
      icon: item.meta.icon,
      videoKey: item.meta.videoKey || '',
    }
  }),
)

let userName = ref<string>('')
userName.value = userInfo.value.userName as string

watch(
  () => ({ ...userInfo.value }),
  (newVal, oldVal) => {
    // console.log('newVal**=', newVal)
    userName.value = newVal.userName as string
  },
)

// 播放视频按钮的显隐
let theLeft = ref('150px')
let videoFlag = ref<boolean>(false)
let timerId = ref<any>(null)

let activePath = ref<string>('')
const activeList = ref<Array<any>>([])
watch(
  router.currentRoute,
  () => {
    // console.log('router.currentRoute=', router.currentRoute.value)

    const deviceType = checkDeviceType()
    if (deviceType !== 'Desktop') {
      // 如果是移动设备
      message.info('请在电脑上打开')
      router.push('/no-content')
    }

    if (router.currentRoute.value) {
      if (router.currentRoute.value.meta.title.length == 4) {
        theLeft.value = '120px'
      } else if (router.currentRoute.value.meta.title.length == 3) {
        theLeft.value = '100px'
      } else if (router.currentRoute.value.meta.title.length == 11) {
        theLeft.value = '260px'
      } else {
        theLeft.value = '150px'
      }
    }

    const headerRouterPath = router.currentRoute.value.path
    // console.log('headerRouterPath=', headerRouterPath)
    // console.log('newRouterList=', newRouterList.value)
    const isHasPath = newRouterList.value.some(item => item == headerRouterPath)
    // console.log('isHasPath=', isHasPath)
    if (isHasPath) {
      nowRouter.value = headerRouterPath
    } else {
      nowRouter.value = ''
    }

    activePath.value = router.currentRoute.value.path

    const newRouteInfo = {
      path: router.currentRoute.value.path,
      title: router.currentRoute.value.meta.title,
    }
    const exists = activeList.value.find(item => item.path === newRouteInfo.path)
    if (!exists) {
      activeList.value.push(newRouteInfo)
    }

    if (timerId.value) {
      clearTimeout(timerId.value)
    }
    videoFlag.value = false
    timerId.value = setTimeout(() => {
      videoFlag.value = true
    }, 600)

    const matched = router.currentRoute.value.matched.concat()

    state.selectedKeys = matched.filter(r => r.name !== 'index').map(r => r.path)

    state.openKeys = matched.filter(r => r.path !== router.currentRoute.value.path).map(r => r.path)
  },
  {
    immediate: true,
  },
)

const toMenuItem = (e: any) => {
  activePath.value = e
  router.push(e)
}

const remove = (targetKey: string) => {
  let lastIndex = 0
  activeList.value.forEach((pane, i) => {
    if (pane.path === targetKey) {
      lastIndex = i - 1
    }
  })
  activeList.value = activeList.value.filter(pane => pane.path !== targetKey)
  if (activeList.value.length && activePath.value === targetKey) {
    if (lastIndex >= 0) {
      activePath.value = activeList.value[lastIndex].path
      toMenuItem(activePath.value)
    } else {
      activePath.value = activeList.value[0].path
      toMenuItem(activePath.value)
    }
  }
}

const onEdit = (targetPath: string) => {
  remove(targetPath)
}
</script>

<template>
  <pro-layout
    v-model:collapsed="state.collapsed"
    v-model:selectedKeys="state.selectedKeys"
    v-model:openKeys="state.openKeys"
    :loading="loading"
    :menu-data="reallyMenuData"
    :breadcrumb="{ routes: breadcrumb }"
    disable-content-margin
    style="min-height: 100vh"
    v-bind="proConfig"
  >
    <template #menuHeaderRender>
      <router-link :to="{ path: '/account' }">
        <img :src="brandStore.documentIcon" />
        <h1>{{ brandStore.documentTitle }}</h1>
      </router-link>
    </template>

    <template #rightContentRender>
      <RightContent :userName="userName" />
    </template>

    <template #breadcrumbRender="{ route, params, routes }">
      <span v-if="routes.indexOf(route) === routes.length - 1">
        <component :is="route.icon" />
        {{ route.breadcrumbName }}
      </span>
      <router-link v-else :to="{ path: route.path, params }">
        <component :is="route.icon" />
        {{ route.breadcrumbName }}
      </router-link>
    </template>

    <SettingDrawer v-model="proConfig" />

    <div class="main">
      <a-tabs
        v-model:activeKey="activePath"
        type="editable-card"
        @change="toMenuItem"
        @edit="onEdit"
        hide-add
      >
        <a-tab-pane
          v-for="(item, index) in activeList"
          :key="item.path"
          :tab="item.title"
          :closable="activeList.length != 1"
        ></a-tab-pane>
      </a-tabs>
    </div>

    <div
      v-if="videoFlag"
      style="position: absolute; top: 92px; left: 120px; z-index: 1"
      :style="{ left: theLeft }"
    >
      <div style="display: inline">
        <NcVideo
          :name="breadcrumb[breadcrumb.length - 1].breadcrumbName"
          :videoUrl="breadcrumb[breadcrumb.length - 1].videoKey"
        ></NcVideo>
      </div>
    </div>

    <div style="margin-bottom: 25px">
      <RouterView v-slot="{ Component, route }">
        <transition name="slide-left" mode="out-in">
          <component :is="Component" :key="route.path" />
        </transition>
      </RouterView>
    </div>
  </pro-layout>

  <div class="footer-text">
    <a>
      {{ brandStore.recordNumber }}
    </a>
  </div>
</template>

<style lang="less" scoped>
.footer-text {
  height: 50px;
  line-height: 50px;
  width: 100%;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.main {
  height: 40px;
  background: #ffffff;
  margin-top: 2px;
  padding-left: 20px;
}
</style>
